﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>辞退信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '辞退员工为必填项', trigger: 'change' }]"
							>
								<template #label>
									<WtmLabelTooltip label="辞退员工" tooltip="被辞退的员工" />
								</template>
								<WtmPersonSelector
									v-model="stateData.vmModel.Entity.PersonId"
									label="辞退员工"
									tooltip="被辞退的员工"
									prop="Entity.PersonId"
									:rules="[{ required: true, message: '辞退员工为必填项', trigger: 'blur' }]"
									@change="onPersonSelected"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_DismissDate_FormItem"
								prop="Entity.DismissDate"
								:rules="[{ required: true, message: '辞退日期为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="辞退日期" tooltip="辞退发生日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.DismissDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ResignType_FormItem"
								prop="Entity.ResignType"
								:rules="[{ required: true, message: '辞退类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="辞退类型" tooltip="辞退类型" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ResignType" clearable class="width100">
									<el-option key="试用期不合格" value="试用期不合格" label="试用期不合格"></el-option>
									<el-option key="严重违纪" value="严重违纪" label="严重违纪"></el-option>
									<el-option key="严重失职或舞弊" value="严重失职或舞弊" label="严重失职或舞弊"></el-option>
									<el-option key="兼岗影响履职且拒不改正" value="兼岗影响履职且拒不改正" label="兼岗影响履职且拒不改正"></el-option>
									<el-option key="欺诈入职或合同无效" value="欺诈入职或合同无效" label="欺诈入职或合同无效"></el-option>
									<el-option key="刑事责任" value="刑事责任" label="刑事责任"></el-option>
									<el-option key="违反保密或竞业" value="违反保密或竞业" label="违反保密或竞业"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_Describe_FormItem"
								prop="Entity.Describe"
								:rules="[{ required: true, message: '辞退说明为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="辞退说明" tooltip="辞退原因或说明" />
								</template>
								<el-input type="textarea" v-model="stateData.vmModel.Entity.Describe" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="SupportingDocumentId_FormItem" prop="Entity.SupportingDocumentId">
								<template #label>
									<WtmLabelTooltip label="证明文件" tooltip="上传辞退证明文件" />
								</template>
								<wtm-upload-file
									v-model="stateData.vmModel.Entity.SupportingDocumentId"
									:allowed-types="['application/pdf', 'image/jpeg', 'image/png', 'image/jpg']"
									clearable
									:multi="false"
								></wtm-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" :disabled="true" :auth="false" />
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model:model-value="stateData.vmModel.Entity.GroupId" label="所属部门" :disabled="true" :auth="false" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrDismissRequestBillApi as api } from '/@/views/hr/syshrdismissrequestbill/api';
import other from '/@/utils/other';
import { ISysHrDismissRequestBillVm } from '/@/views/hr/syshrdismissrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { useUserInfo } from '/@/stores/userInfo';
import { getCurrentUserMainGroupId } from '/@/utils/userGroup';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	SUBMITTING: '提交中',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

// 获取用户信息store
const userInfoStore = useUserInfo();

const stateData = reactive<IViewModel<ISysHrDismissRequestBillVm>>({
	vmModel: {
		Entity: {
			PersonId: null,
			DismissDate: null,
			ResignType: null,
			Describe: null,
			OrgId: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			StaffNo: null,
			Name: null,
			SupportingDocumentId: [],
		},
		IsMyApprove: false,
		ActionName: null,
		Remark: null,
	},

	AllSysGroups: [] as any[],
	selectedPersonInfo: null as any, // 存储选中的完整人员信息
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

// 公共的响应处理函数
const handleApiResponse = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
	}

	emit('refresh');

	// 统一处理ID设置
	if (response?.Entity?.ID) {
		stateData.vmModel.Entity = response.Entity;
	} else if (response?.ID) {
		stateData.vmModel.Entity.ID = response.ID;
	}

	// 根据操作类型处理不同逻辑
	if (isSubmit) {
		closeDialog();
	} else {
		hasSavedOnce.value = true;
	}

	loading.value = false; // 重置loading状态

	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的表单提交函数
const submitForm = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			beforeSubmit();
			apiCall()
				.then((response: any) => handleApiResponse(response, isSubmit))
				.catch(handleError);
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	submitForm(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false
	);
};

// 提交
const onSubmit = () => {
	submitForm(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = BILL_STATUS.SUBMITTING;
		},
		true
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [billCode] = await Promise.allSettled([api().getBillCode()]);

	// 处理成功的结果
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;

	// 设置默认部门为当前用户的主要部门
	if (!stateData.vmModel.Entity.GroupId) {
		stateData.vmModel.Entity.GroupId = getCurrentUserMainGroupId();
	}
};

// 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || person.staffNo || '';
		stateData.vmModel.Entity.Name = person.Name || person.name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = '';
		stateData.vmModel.Entity.Name = '';
		stateData.vmModel.Entity.OrgId = '';
		stateData.vmModel.Entity.GroupId = '';
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 确保用户信息已加载
		await userInfoStore.setUserInfos();
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: hasEntityId.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
